#include <avr/io.h>
#include "key.h"
#include "global.h"
#include "OLED.h"
#include "spi.h"

#define SPI_HW_MODE             1

#if SPI_HW_MODE
void spi_init(void)
{
	SPIC.CTRL = SPI_ENABLE_bm | SPI_MASTER_bm | SPI_PRESCALER0_bm;
}
uint8_t spi_play_one_byte(uint8_t data)
{
	SPIC.DATA = data;
	while(!testbit(SPIC.STATUS,7));
	return SPIC.DATA;
}

#else
inline void spi_init(void)
{

}
uint8_t spi_play_one_byte(uint8_t data)
{
	uint8_t ret_val = 0, mask = 0x80;

	do {
		if(mask & data) {
			SET_MOSI();
		} else {
			CLR_MOSI();
		}
		//delay();
		TOGGLE_SCK();
		//delay();
		if(GET_MISO()) {
			ret_val |= mask;
		}
		mask = mask >> 1;
		TOGGLE_SCK();
		//delay();
	} while(mask);

	return ret_val;
}
#endif
void spi_read_data(uint8_t addr_H, uint16_t addr_L, uint8_t *read_buff, uint16_t len)
{
	ROM_Active();

	spi_play_one_byte(0x03);
	spi_play_one_byte(addr_H);
	spi_play_one_byte((uint8_t)(addr_L >> 8));
	spi_play_one_byte((uint8_t)addr_L);

	while(len--) {
		*read_buff++ = spi_play_one_byte(0x00);
	}

	ROM_Deactive();
}

